package com.sxbbc.plat.controller.jz;

import java.io.InputStream;
import java.sql.Date;
import java.util.List;

import com.sxbbc.common.core.entity.jz.CCustomer;
import com.sxbbc.common.core.entity.jz.CCustomerAuthen;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.service.system.mode.ModeService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.enums.RandNumType;
import com.sxbbc.common.basics.files.RestUploadFileInfo;
import com.sxbbc.common.basics.files.UploadUtils;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.date.DateUtil;
import com.sxbbc.common.basics.utils.qr.QRCodeUtil;
import com.sxbbc.common.basics.utils.radoms.RandNumUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.service.system.solr.SolrproductService;
import com.sxbbc.common.core.service.system.solr.entity.SolrProductDto;
import com.sxbbc.plat.service.CustomerService;
import com.sxbbc.plat.service.TaskService;

@RestController
public class TestController {

    Logger log = LogManager.getLogger(TestController.class);

    @Autowired
    private ICCustomerService customerService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ICCustomerAuthenService icCustomerAuthenService;
    @Autowired
    private IChickenCouponService iChickenCouponService;
    @Autowired
    private CustomerService customerService2;
    @Autowired
    private SolrproductService solrproductService;
    @Autowired
    private ModeService modeService;
    @Autowired
    private IChickenFundService iChickenFundService;
    @Autowired
    private IChickenBonusService iChickenBonusService;
    @Autowired
    private IChickenOrderService iChickenOrderService;

//    @Autowired
//    private  ICOrderService icOrderService;
//    @RequestMapping("/inviteCode")
//    @ResponseBody
//    public void inviteCode() {
//        List<COrder> list = icOrderService.list();
//
//    }

//    @Autowired
//    private AddresszzMapper addresszzMapper;
//    @Autowired
//    private AddressMapper addressMapper;
//
//    @RequestMapping("/geChickenCoupon")
//    @ResponseBody
//    public void geChickenCoupon() {
//        QueryWrapper<ChickenCoupon> wrapper = new QueryWrapper<>();
//        wrapper.ge("id", 27900);
//        List<ChickenCoupon> list = iChickenCouponService.list(wrapper);
//        for (ChickenCoupon item : list) {
//            QueryWrapper<ChickenOrder> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("order_code", item.getOrderCode());
//            ChickenOrder chickenOrder = iChickenOrderService.getOne(queryWrapper);
//            item.setSource(OrderTypeEnums.getName(chickenOrder.getOrderType()));
//            item.setOrderNo(CalcuUtils.getInstance().getOrderCode("COG"));
//            iChickenCouponService.updateById(item);
//        }
//        System.out.println("ok");
//    }
//
//    @Autowired
//    private ICCustomerOldService icCustomerOldService;
//
//    @RequestMapping("/geidcard")
//    @ResponseBody
//    public void geidcard() {
//        QueryWrapper<CCustomerOld> wrapper = new QueryWrapper<>();
//        List<CCustomerOld> list = icCustomerOldService.list(null);
//        for (CCustomerOld item : list) {
//            if (StringUtils.isNotBlank(item.getIdcard()) && StringUtils.isNotBlank(item.getRealname())) {
//                CCustomerAuthen authen = new CCustomerAuthen();
//                authen.setCid(item.getId());
//                authen.setRealName(item.getRealname());
//                authen.setIdcard(item.getIdcard());
//                authen.setCreateTime(new Date());
//                authen.setSex(0);
//                authen.setCheckTime(new Date());
//                authen.setAuthType(1);
//                authen.setIsLongLasting(0);
//                authen.setStatus(2);
//                icCustomerAuthenService.save(authen);
//            }
//        }
//        System.out.println("ok");
//    }
//
//    /**
//     * 地址
//     */
//    @RequestMapping("/address")
//    @ResponseBody
//    public void geaddress() {
//        List<CCustomer> list = customerService.list();
//        for (CCustomer customer : list) {
//            if (StringUtils.isBlank(customer.getInviteCode()) && customer.getProId() != null && customer.getProId() < 110000) {
//                Integer proId = customer.getProId();
//                Integer cityId = customer.getCityId();
//                Integer areaId = customer.getAreaId();
//                if (proId != null && cityId != null && areaId != null) {
//                    Addresszz pro = addresszzMapper.selectById(proId);
//                    Addresszz city = addresszzMapper.selectById(cityId);
//                    Addresszz area = addresszzMapper.selectById(areaId);
//                    if (pro != null && city != null && area != null) {
//                        System.out.println(pro.getName() + " " + city.getName() + " " + area.getName());
//                        QueryWrapper<Address> wrapper = new QueryWrapper<>();
//                        wrapper.eq("name", pro.getName()).eq("pid", 0);
//                        Address one = addressMapper.selectOne(wrapper);
//                        if (one != null) {
//                            customer.setProId(one.getId());
//                        } else {
//                            System.out.println("省未找到" + pro.getName());
//                        }
//                        QueryWrapper<Address> wrapper2 = new QueryWrapper<>();
//                        wrapper2.eq("name", city.getName());
//                        Address one2 = addressMapper.selectOne(wrapper2);
//                        if (one2 != null) {
//                            customer.setCityId(one2.getId());
//                        } else {
//                            System.out.println("市未找到" + city.getName());
//                        }
//                        QueryWrapper<Address> wrapper3 = new QueryWrapper<>();
//                        wrapper3.eq("name", area.getName());
//                        if ("长安镇".equals(area.getName())) {
//                            wrapper3.eq("pid", 441900);
//                        }
//                        if ("南城街道".equals(area.getName())) {
//                            wrapper3.eq("pid", 441900);
//                        }
//                        if ("东城街道".equals(area.getName())) {
//                            wrapper3.eq("pid", 441900);
//                        }
//                        if ("白云区".equals(area.getName())) {
//                            wrapper3.eq("pid", 440100);
//                        }
//                        Address one3 = addressMapper.selectOne(wrapper3);
//                        if (one3 != null) {
//                            customer.setAreaId(one3.getId());
//                        } else {
//                            System.out.println("区未找到" + area.getName());
//                        }
//                        boolean save = customerService.updateById(customer);
//                        if (!save) {
//                            System.out.println("fail");
//                        }
//                    }
//
//                }
//            }
//        }
//        System.out.println("ok");
//
//    }

    /**
     * 生成推荐码
     */
    @RequestMapping("/inviteCode")
    @ResponseBody
    public void inviteCode() {
        List<CCustomer> list = customerService.list();
        for (CCustomer customer : list) {
//            if (StringUtils.isBlank(customer.getInviteCode())) {
                // 个人邀请码
//                String code = "code";
//                do {
//                    code = Encode.getRandomNum(8, 2);
//                } while (customerService.getByInviteCode(code) != null);
//                customer.setInviteCode(code);
//                customer.setPhone(customer.getLogin());
//                customer.setOpenidWx(null);
//                if (StringUtils.isNotBlank(customer.getRealName())) {
//                    customer.setAuthen(StaticUtils.STATUS_YES);
//                } else {
//                    customer.setAuthen(StaticUtils.STATUS_NO);
//                }
                //认证

                //APP个人推荐码
                InputStream is = QRCodeUtil.getInstance().encode("http://h5.danongkj.cn/jzz/#/pages/Tabbar/User/index?inviteCode=" + customer.getInviteCode() + "&parentPhone=" + customer.getLogin());
                String filename = DateUtil.getInstance().currentTimeMillis() + RandNumUtils.getInstance().get(RandNumType.NUMBER, 5) + "." + QRCodeUtil.getInstance().FORMAT_NAME;
                RestUploadFileInfo r = UploadUtils.getInstance().uploadFile(is, filename);
                if (r.isStatus()) {
                    customer.setQrApp(r.getData());
                }
                //公众个人推荐码
                is = QRCodeUtil.getInstance().encode("http://h5.danongkj.cn/jzz/#/pages/Tabbar/User/index?inviteCode=" + customer.getInviteCode() + "&parentPhone=" + customer.getLogin());
                filename = DateUtil.getInstance().currentTimeMillis() + RandNumUtils.getInstance().get(RandNumType.NUMBER, 5) + "." + QRCodeUtil.getInstance().FORMAT_NAME;
                r = UploadUtils.getInstance().uploadFile(is, filename);
                if (r.isStatus()) {
                    customer.setQrWx(r.getData());
                }
//			//小程序个人推荐码
//			is = QRCodeUtil.getInstance().encode("http://h5.danongkj.cn/share/program?inviteCode=" + customer.getInviteCode());
//			filename = DateUtil.getInstance().currentTimeMillis() + RandNumUtils.getInstance().get(RandNumType.NUMBER, 5) + "." + QRCodeUtil.getInstance().FORMAT_NAME;
//			r = UploadUtils.getInstance().uploadFile(is, filename);
//			if (r.isStatus()) {
//				customer.setQrProgram(r.getData());
//			}
                customerService.updateById(customer);
//            }
        }
        System.out.println("ok");
    }

    @RequestMapping("/updateParent")
    public void updateParent() {
        customerService2.updateParent(10007, 10001);
    }

    //region 测试solr功能

    /**
     * 新增solr测试数据
     *
     * @return
     */
    @RequestMapping("/addSolrData")
    @ResponseBody
    public Object testSolr() {
        String proCode = "113";
        SolrProductDto dto = new SolrProductDto();
        dto.setActivitySign("activitySign");
        dto.setBid(1);
        dto.setbTypeName("bTypeName");
        dto.setDescval("descval");
        dto.setFclassid(1);
        dto.setId("id1");
        dto.setKeyword("keyword");
        dto.setPid(1);
        dto.setPname("pname");
        dto.setPoint("0.00");
        dto.setProoldprice("0.00");
        dto.setProprice("0.00");
        dto.setPurl("purl");
        dto.setSaleqty(1);
        dto.setSclassid(2);
        dto.setSort(1);
        dto.setStime(new Date(192316754L));
        dto.setTclassid(3);
        dto.setType(1);
        solrproductService.addProduct(dto);
        return solrproductService.selectById(proCode);
    }

    @RequestMapping("/deleteSolrData")
    @ResponseBody
    public Object testSolr(String id) {
        return solrproductService.deleteProduct(id);
    }

    //endregion

    @RequestMapping("/updateRealName")
    public RestResponse updateRealName() {
        QueryWrapper<CCustomer> queryWrapper = new QueryWrapper<CCustomer>();
        queryWrapper.eq("authen", StaticUtils.STATUS_YES);
        List<CCustomer> list = customerService.list(queryWrapper);
        for (CCustomer c : list) {
            try {
                QueryWrapper<CCustomerAuthen> authenWrapper = new QueryWrapper<CCustomerAuthen>();
                authenWrapper.eq("cid", c.getId());
                CCustomerAuthen authen = icCustomerAuthenService.getOne(authenWrapper);
                if (authen != null) {
                    c.setRealName(authen.getRealName());
                    customerService.updateById(c);
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        return GetRest.getSuccess("SUCCESS");
    }

    @RequestMapping("/validBankcode")
    public RestResponse validBankcode() {
        String realname = "王柏生";
        String idCard = "350524199712223536";
        String bankCard = "6212262010021674434";
        String phone = "15014773003";
        return CalcuUtils.getInstance().validBankcode4(realname, idCard, bankCard, phone);
    }

    @RequestMapping("/testLog")
    public RestResponse testLog() {
        log.info("测试日志记录");
        log.info("message", 1, 2);
        return GetRest.getSuccess("");
    }

    @RequestMapping("/testTask")
    public RestResponse testTask() {
        log.info("定时解冻任务开始...");
        try {
            taskService.autoHandleFreezingAccount();
        } catch (Exception e) {
            log.info("定时任务异常结束：" + e.getMessage());
            e.printStackTrace();
        }
        log.info("定时解冻任务结束...");
        return GetRest.getSuccess("SUCCESS");
    }

    /**
     * 释放基金
     *
     * @return
     */
//    @RequestMapping("/testFundTask")
//    public RestResponse testFundTask() {
//        log.info("定时解冻任务开始...");
//        try {
//			iChickenFundService.setTime();
//            modeService.handleFrozenFund();
//        } catch (Exception e) {
//            log.info("定时任务异常结束：" + e.getMessage());
//            e.printStackTrace();
//        }
//        log.info("定时解冻任务结束...");
//        return GetRest.getSuccess("SUCCESS");
//    }

    /**
     * 释放提鸡券
     *
     * @return
     */
//    @RequestMapping("/testCuponTask")
//    public RestResponse testCouponTask() {
//        log.info("定时释放提鸡券成待使用状态任务开始...");
//        try {
//            iChickenCouponService.setTime();
//            iChickenCouponService.handleFrozenCoupon();
//        } catch (Exception e) {
//            log.info("定时释放提鸡券成待使用状态任务异常结束：" + e.getMessage());
//            e.printStackTrace();
//        }
//        log.info("定时释放提鸡券成待使用状态任务结束...");
//        return GetRest.getSuccess("SUCCESS");
//    }

//    @RequestMapping("/testBonus/{id}")
//    public RestResponse testBonus(@PathVariable("id") Integer id) {
//        log.info("定时释放提鸡券成待使用状态任务开始...");
//        try {
//            ChickenOrder chickenOrder = iChickenOrderService.getById(id);
//            modeService.generateFarmBonusRecordByBonusDay(chickenOrder);
//        } catch (Exception e) {
//            log.info("定时释放提鸡券成待使用状态任务异常结束：" + e.getMessage());
//            e.printStackTrace();
//        }
//        log.info("定时释放提鸡券成待使用状态任务结束...");
//        return GetRest.getSuccess("SUCCESS");
//    }
}
